#!/bin/bash

# =====================================================
# Docker MySQL 独立安装和连接脚本 (Linux/Mac版本)
# 功能：自动安装、配置和连接MySQL数据库
# =====================================================

set -e  # 遇到错误时退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

print_header() {
    echo -e "${BLUE}===============================================${NC}"
    echo -e "${BLUE}    Docker MySQL 独立安装和连接脚本${NC}"
    echo -e "${BLUE}===============================================${NC}"
    echo ""
}

# 检查命令是否存在
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# 等待用户输入
wait_for_input() {
    echo ""
    read -p "按 Enter 键继续..."
    echo ""
}

# 主函数
main() {
    print_header

    # 设置变量
    MYSQL_CONTAINER_NAME="quantitative_mysql"
    MYSQL_ROOT_PASSWORD="quantitative_password"
    MYSQL_DATABASE="quantitative_advanced"
    MYSQL_USER="quantitative_user"
    MYSQL_PASSWORD="quantitative_password"
    MYSQL_PORT="3306"
    PHPMYADMIN_PORT="8080"
    PHPMYADMIN_CONTAINER_NAME="quantitative_phpmyadmin"

    # 步骤1：检查Docker是否安装
    echo "[1/6] 检查Docker环境..."
    if ! command_exists docker; then
        print_error "Docker未安装，请先安装Docker"
        echo "Ubuntu/Debian: sudo apt-get install docker.io"
        echo "CentOS/RHEL: sudo yum install docker"
        echo "macOS: 下载Docker Desktop from https://www.docker.com/products/docker-desktop"
        exit 1
    fi
    print_success "Docker已安装"

    # 步骤2：检查Docker是否运行
    echo "[2/6] 检查Docker运行状态..."
    if ! docker info >/dev/null 2>&1; then
        print_error "Docker未运行，请先启动Docker服务"
        echo "Linux: sudo systemctl start docker"
        echo "macOS: 启动Docker Desktop应用"
        
        read -p "启动Docker后按 Enter 键继续，或按 Ctrl+C 退出..."
        
        # 再次检查
        if ! docker info >/dev/null 2>&1; then
            print_error "Docker仍未运行，请手动启动Docker后重新运行此脚本"
            exit 1
        fi
    fi
    print_success "Docker运行正常"

    # 步骤3：检查现有容器
    echo "[3/6] 检查现有MySQL容器..."
    if docker ps -a --format "table {{.Names}}" | grep -q "^${MYSQL_CONTAINER_NAME}$"; then
        print_warning "发现现有MySQL容器：${MYSQL_CONTAINER_NAME}"
        echo ""
        echo "选择操作："
        echo "1. 停止并删除现有容器，重新创建"
        echo "2. 启动现有容器"
        echo "3. 退出"
        echo ""
        read -p "请选择 (1-3): " choice
        
        case $choice in
            1)
                echo "正在停止并删除现有容器..."
                docker stop $MYSQL_CONTAINER_NAME >/dev/null 2>&1 || true
                docker rm $MYSQL_CONTAINER_NAME >/dev/null 2>&1 || true
                print_success "现有容器已删除"
                ;;
            2)
                echo "正在启动现有容器..."
                docker start $MYSQL_CONTAINER_NAME
                show_connection_info
                exit 0
                ;;
            3)
                echo "退出脚本"
                exit 0
                ;;
            *)
                print_error "无效选择，退出脚本"
                exit 1
                ;;
        esac
    fi

    # 步骤4：拉取MySQL镜像
    echo "[4/6] 拉取MySQL 8.0镜像..."
    if ! docker pull mysql:8.0; then
        print_error "无法拉取MySQL镜像"
        exit 1
    fi
    print_success "MySQL镜像拉取完成"

    # 步骤5：创建并启动MySQL容器
    echo "[5/6] 创建并启动MySQL容器..."
    if ! docker run -d \
        --name $MYSQL_CONTAINER_NAME \
        --restart unless-stopped \
        -p $MYSQL_PORT:3306 \
        -e MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD \
        -e MYSQL_DATABASE=$MYSQL_DATABASE \
        -e MYSQL_USER=$MYSQL_USER \
        -e MYSQL_PASSWORD=$MYSQL_PASSWORD \
        mysql:8.0 \
        --character-set-server=utf8mb4 \
        --collation-server=utf8mb4_unicode_ci \
        --default-authentication-plugin=mysql_native_password; then
        print_error "无法创建MySQL容器"
        exit 1
    fi
    print_success "MySQL容器创建成功"

    # 步骤6：等待MySQL启动
    echo "[6/6] 等待MySQL服务启动..."
    count=0
    max_attempts=20
    
    while [ $count -lt $max_attempts ]; do
        if docker exec $MYSQL_CONTAINER_NAME mysqladmin ping -h localhost -u root -p$MYSQL_ROOT_PASSWORD >/dev/null 2>&1; then
            print_success "MySQL服务启动完成"
            break
        fi
        
        count=$((count + 1))
        echo "等待中... ($count/$max_attempts)"
        sleep 3
    done
    
    if [ $count -eq $max_attempts ]; then
        print_error "等待超时，MySQL可能启动失败"
        echo "检查容器日志："
        docker logs $MYSQL_CONTAINER_NAME
        exit 1
    fi

    # 显示连接信息
    show_connection_info

    # 询问是否安装phpMyAdmin
    install_phpmyadmin

    # 测试数据库连接
    test_database_connection

    # 显示完成信息
    show_completion_info
}

# 显示连接信息
show_connection_info() {
    echo ""
    echo "==============================================="
    echo "           MySQL 安装完成！"
    echo "==============================================="
    echo ""
    print_info "📊 数据库连接信息："
    echo "   主机地址: localhost (或 127.0.0.1)"
    echo "   端口:     $MYSQL_PORT"
    echo "   数据库:   $MYSQL_DATABASE"
    echo "   用户名:   $MYSQL_USER"
    echo "   密码:     $MYSQL_PASSWORD"
    echo ""
    print_info "🔧 管理员信息："
    echo "   用户名:   root"
    echo "   密码:     $MYSQL_ROOT_PASSWORD"
    echo ""
    print_info "🐳 容器管理命令："
    echo "   启动容器: docker start $MYSQL_CONTAINER_NAME"
    echo "   停止容器: docker stop $MYSQL_CONTAINER_NAME"
    echo "   删除容器: docker rm $MYSQL_CONTAINER_NAME"
    echo "   查看日志: docker logs $MYSQL_CONTAINER_NAME"
    echo ""
}

# 安装phpMyAdmin
install_phpmyadmin() {
    echo "==============================================="
    echo "是否安装phpMyAdmin Web管理界面？"
    echo "==============================================="
    read -p "安装phpMyAdmin? (y/n): " install_choice
    
    if [[ $install_choice =~ ^[Yy]$ ]]; then
        echo "正在安装phpMyAdmin..."
        
        # 检查是否已存在phpMyAdmin容器
        if docker ps -a --format "table {{.Names}}" | grep -q "^${PHPMYADMIN_CONTAINER_NAME}$"; then
            print_warning "发现现有phpMyAdmin容器，正在删除..."
            docker stop $PHPMYADMIN_CONTAINER_NAME >/dev/null 2>&1 || true
            docker rm $PHPMYADMIN_CONTAINER_NAME >/dev/null 2>&1 || true
        fi
        
        if docker run -d \
            --name $PHPMYADMIN_CONTAINER_NAME \
            --restart unless-stopped \
            -p $PHPMYADMIN_PORT:80 \
            -e PMA_HOST=host.docker.internal \
            -e PMA_PORT=$MYSQL_PORT \
            phpmyadmin/phpmyadmin; then
            
            print_success "phpMyAdmin安装成功"
            echo ""
            print_info "🌐 phpMyAdmin访问信息："
            echo "   URL:     http://localhost:$PHPMYADMIN_PORT"
            echo "   用户名:  root 或 $MYSQL_USER"
            echo "   密码:    $MYSQL_ROOT_PASSWORD 或 $MYSQL_PASSWORD"
            echo ""
            
            # 在Linux环境下尝试打开浏览器
            if command_exists xdg-open; then
                print_info "🚀 正在打开phpMyAdmin..."
                sleep 3
                xdg-open "http://localhost:$PHPMYADMIN_PORT" >/dev/null 2>&1 &
            elif command_exists open; then
                # macOS
                print_info "🚀 正在打开phpMyAdmin..."
                sleep 3
                open "http://localhost:$PHPMYADMIN_PORT"
            else
                print_info "请手动在浏览器中访问: http://localhost:$PHPMYADMIN_PORT"
            fi
        else
            print_error "phpMyAdmin安装失败"
        fi
    fi
}

# 测试数据库连接
test_database_connection() {
    echo ""
    echo "==============================================="
    echo "是否测试数据库连接？"
    echo "==============================================="
    read -p "测试连接? (y/n): " test_choice
    
    if [[ $test_choice =~ ^[Yy]$ ]]; then
        echo "正在测试数据库连接..."
        
        if docker exec $MYSQL_CONTAINER_NAME mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -D $MYSQL_DATABASE -e "SELECT 'MySQL连接成功!' AS status, NOW() AS current_time;"; then
            print_success "数据库连接测试成功！"
        else
            print_error "数据库连接测试失败"
            echo "请检查容器状态: docker ps"
        fi
    fi
}

# 显示完成信息
show_completion_info() {
    echo ""
    echo "==============================================="
    echo "           安装完成！"
    echo "==============================================="
    echo ""
    print_info "💡 下一步操作："
    echo "   1. 使用提供的连接信息连接数据库"
    echo "   2. 运行你的应用程序"
    echo "   3. 访问 phpMyAdmin 进行数据库管理 (如果已安装)"
    echo ""
    print_info "📝 重要提示："
    echo "   - 容器会在系统重启后自动启动"
    echo "   - 数据保存在Docker卷中，删除容器不会丢失数据"
    echo "   - 如需备份数据，请使用mysqldump命令"
    echo ""
    
    wait_for_input
}

# 脚本入口点
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi
